package top.kaoshanji.p3ch11b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.*;

/**
 * 代码清单-p3ch11b-367页a：ExecutorService接口的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/5 11:23
 */
public class FileDownloader {

    private static final Logger logger = LogManager.getLogger(FileDownloader.class);

    public static void main(String[] args) throws MalformedURLException {
        logger.info("...代码清单-p3ch11b-367页a：ExecutorService接口的使用示例...");

        FileDownloader downloader = new FileDownloader();
        String rootPath = FileConstant.LOCAL_ROOT_PATH.concat("p3ch11b367页a\\");
        downloader.download(new URL("http://www.baidu.com"), Paths.get(rootPath.concat("baidu.txt")));
        downloader.download(new URL("http://www.sina.com.cn"), Paths.get(rootPath.concat("sina.txt")));
        downloader.close();
    }

    private final ExecutorService executor = Executors.newFixedThreadPool(10);

    public boolean download(final URL url, final Path path) {

        Future<Path> future = executor.submit(new Callable<Path>() {
            @Override
            public Path call() throws Exception {

                try {
                    InputStream is = url.openStream();
                    Files.copy(is, path, StandardCopyOption.REPLACE_EXISTING);
                    return path;
                }catch (IOException e) {
                    return null;
                }
            }
        });

        try {
            return future.get() != null ? true : false;
        }  catch (InterruptedException | ExecutionException e) {
            return false;
        }

    }

    public void close() {

        executor.shutdown();
        try {
            if (!executor.awaitTermination(3, TimeUnit.MINUTES)) {
                executor.shutdownNow();
                executor.awaitTermination(1, TimeUnit.MINUTES);
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }

    }

}
